(function($, $page){
	var $parentGrid = $('#jGridForShifting', $page.data("_parent")), $grid = $('#gridForShiftingBatchAdding', $page), 
	$form = $('form:first', $page), $wcTmp = $('#workcenterTemplate', $page), dateFormat = 'yyyy-MM-dd', dateTimeFormat= 'yyyy-MM-dd HH:mm', 
	$periodSelect = $('#periodSelect', $form), perDay = 24 * 60 * 60 * 1000,
	getNextDate = function(date) {
		if (date.getTime) {
			return new Date(date.getTime() + perDay);
		} else {
			return new Date(date.parseDate(dateFormat).getTime() + perDay);
		}
	},
	columns = [
		{field: 'id', group: 'ids', type: 'checkbox', width: 22},
		{field: 'personnelCode', text: '人员编号', width: 150},
		{field: 'personnelName', text: '姓名', width: 150},
		{field: 'workCenterText', text: '工作中心', width: 150},
		/*{field: 'personnelTypeCode', text: '人员类型', type: 'select', width: 150}*/
	],
	rowIndex = 0, 
	trId = 'trForShiftingBatchAdd',
	appendRow = function(){
		var $tr = $('<tr/>');
		$.each(columns, function(){
			var $td = $('<td/>'), $wrap = $('<div class="editCell"/>');
			if (this.type == 'checkbox') {
				var $input = $('<input type="checkbox"/>');
				$wrap.append($input);
			} else if (this.type == 'select') {
				var $select = $wcTmp.clone().show().removeAttr('id');
				$wrap.append($select);
				$select[0].selectedIndex = -1;
			} else {
				var $input = $('<input type="text"/>');
				$wrap.append($input);
			}
			var $input = $('>select:first', $wrap);
			if($input.length == 0) {
				$input = $('>input:first', $wrap);
			}
			$input.attr({
				name: this.group || trId + rowIndex + '.' + this.field
			});
			switch (this.field) {
				case 'personnelCode':
					$input.attr({
						lookupGroup: trId + rowIndex + '_personnel',
						id: trId + rowIndex + '_personnel.personnelCode',
						labelFields: 'personnelCode,personnelName',
						postField: 'personnelCode',
						suggestFields: 'personnelCode,personnelName,workCenterCode,workCenterText',
						suggestUrl: hostUrl + '/personnel/personnelSuggest',
						remote: hostUrl + '/personnel/validatePersonnel',
						warn: '人员编号不存在！'
					}).addClass('required');
					break;
				case 'personnelName':
					$input.attr({
						lookupGroup: trId + rowIndex + '_personnel',
						id: trId + rowIndex + '_personnel.personnelName',
						readonly:true
					});
					$input.after($('<input type="hidden"/>').attr({
						lookupGroup: trId + rowIndex + '_personnel',
						id: trId + rowIndex + '_personnel.workCenterCode',
						name: trId + rowIndex + '.workcenterCode'
					}));
					break;
				case 'workCenterText':
					$input.attr({
						lookupGroup: trId + rowIndex + '_personnel',
						id: trId + rowIndex + '_personnel.workCenterText',
						readonly:true
					});
					break;
				case 'id':
					break;
				default:
					$input.addClass('required');
					break;
			}
			$td.append($wrap).appendTo($tr);
		});
		$tr.appendTo($('tbody', $grid));
		$grid.jGrid('refresh');
		$tr.initUI();
		rowIndex ++;
	},
	setFieldValue = function($field, obj) {
		var name = $field.attr('name');
		name = name.substring(name.indexOf('.') + 1);
		if ($field.is('.date')) {
			obj[name] = $field.val().parseDate(dateTimeFormat);
		} else {
			obj[name] = $field.val();
		}
	},
	// 判断数据列表是否无效
	validateShiftingList = function(shiftings, theDate) {
		var isInvalid = true;
		DWZ.ajax({
			url: hostUrl + '/shifting/validateShiftingList',
			async: false,
			data: {
				theDate: theDate,
				shiftings: JSON.stringify(shiftings)
			},
			alert: false,
			success: function(json) {
				isInvalid = json.data;
			}
		});
		return isInvalid;
	},
	common = ShiftingCommon();
	common.initPage($page);
	
	$grid.jGrid({
		height: 280,
		autoLoad: false,
		columnresizeable: true,
		orderable: false,
		pageable: false,
		trselectable: false,
		hasBorder: true,
		columns: columns,
		gridbars: [
			{icon: 'add', text: '添加', target: 'confirmTodo', action: function(){
				if ($('tbody>tr>td.noData', $grid).length == 1) {
					$('tbody', $grid).empty();
				}
				appendRow();
			}},
			{icon: 'delete', text: '移除', target: 'confirmTodo', action: function(){
				var hasSelected = false;
				$('tbody input[type=checkbox]', $grid).each(function(){
					if(this.checked){
						hasSelected = true;
						return false;
					}
				});
				if (!hasSelected) {
					alertMsg.error(DWZ.msg("alertSelectMsg"));
				} else {
					alertMsg.confirm('确认要移除选中的行吗？', {okCall: function(){
						$('tbody input[type=checkbox]', $grid).each(function(){
							if(this.checked){
								$(this).parents('tr:first').remove();
							}
						});
						$grid.jGrid('refresh');
					}});
				}
			}}
		]
	});
	var $start = $('#startDateTime', $form), $end = $('#endDateTime', $form);
	
	$('#saveBtn', $page).on('click', function(){
		var $f = $(this).parents('form:first');
		if (!$f || !$f.valid()) {
			return false;
		}
		
		var startDateTime = $('#startDateTime', $page).val().parseDate(dateTimeFormat),
		endDateTime = $('#endDateTime', $page).val().parseDate(dateTimeFormat);
		
		if (startDateTime.getTime() >= endDateTime.getTime() || endDateTime.getTime() - startDateTime.getTime() > perDay) {
			$('#startDateTime,#endDateTime', $page).addClass('error');
			alertMsg.error('起止时间不合法！');
			return false;
		}
		
		var shiftings = new Array(),
		theDate = $('#theDate', $form).val();
		
		$('tbody>tr', $grid).each(function(){
			var $tr = $(this);
			if ($('>.noData', $tr).length == 1) {
				alertMsg.error('无有效的数据可保存！');
				return false;
			}
			var shifting = {
				id: 0,
				theDate: theDate.parseDate(dateFormat),
				materialCode: $('[name=materialCode]', $form).val(),
				shiftingWorkcenterCode: $('#shiftingWorkcenterCode', $page).val(),
				startDateTime: startDateTime,
				endDateTime: endDateTime,
				memo: $('#memo', $page).val()
			};
			$('input', $tr).each(function(){
				var $this = $(this);
				if ($this.is('[name=ids]')) {
					return true;
				}
				setFieldValue($this, shifting);
			});
			$('select', $tr).each(function(){
				setFieldValue($(this), shifting);
			});
			shiftings.push(shifting);
		});
		// 如果数据校验失败
		if (validateShiftingList(shiftings, theDate)) {
			if ($('#alertMsgBox').is(':visible')) {
				return false;
			}
			alertMsg.error('数据校验失败，时间段存在冲突或者时间超过24小时，请检查数据！');
			return false;
		}
		if (shiftings.length > 0) {
			DWZ.ajax({
				url: hostUrl + '/shifting/batchSaveShiftingList',
				async: false,
				data: {
					shiftings: JSON.stringify(shiftings)
				},
				success: function(json) {
					$parentGrid.jGrid('loadData');
					$grid.jGrid('clearData');
				}
			});
		}
		return false;
	});
	
	$('#closeDialog', $page).on('click', function(){
		if ($('tbody>tr>.noData', $grid).length == 1) {
			$.pdialog.close($page);
		} else {
			alertMsg.confirm('列表中的数据未保存，确认要取消吗？', {
				okCall: function(){
					$.pdialog.close($page);
				}
			});
		}
	});
})(jQuery, DWZ.context());